package com.heima.pd.service;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;
import com.heima.pd.aggregation.entity.AuthUser;
import com.heima.pd.aggregation.service.IAuthUserService;
import com.heima.pd.common.constant.Constants;
import com.heima.pd.common.dtos.AppHttpCodeEnum;
import com.heima.pd.common.dtos.ResponseResult;
import com.heima.pd.common.model.LoginBody;
import com.heima.pd.common.redis.RedisCache;
import com.heima.pd.common.utils.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import sun.misc.MessageUtils;

import java.util.List;
import java.util.Map;


/**
 * 登录校验方法
 */
@Component
public class SysLoginService {


    @Autowired
    private RedisCache redisCache;

    @Autowired
    private IAuthUserService authUserService;

    /**
     * 登录验证
     *
     * @param account 用户账号
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public ResponseResult login(String account, String password, String code, String uuid) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);

        if (captcha == null) {
           return ResponseResult.errorResult(AppHttpCodeEnum.CAPTCHA_EXPRIRE);
        }

        if (!code.equalsIgnoreCase(captcha)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.CAPTCHA_ERROR);
        }

        // 用户验证 校验用户账号 密码 是否匹配
        //1.参数校验
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }
        Wrapper wrapper = new QueryWrapper<AuthUser>();
        ((QueryWrapper) wrapper).eq("account", account);

        List<AuthUser> list = authUserService.list(wrapper);
        if (list != null && list.size() == 1) {
            AuthUser authUser = list.get(0);
            //获取用户输入的密码 和 查询信息中的盐 生成新的密文
            String pswd = DigestUtils.md5DigestAsHex((password + authUser.getSalt()).getBytes());
            if (authUser.getPassword().equals(pswd)) {
                Map<String, Object> map = Maps.newHashMap();

                authUser.setPassword("");
                authUser.setSalt("");
                map.put("token", AppJwtUtil.getToken(authUser.getId().longValue()));//jwt 生成密文 token
                map.put("user", authUser);//User隐藏了敏感信息
                return ResponseResult.okResult(map);//返回给前台 让前台存放进请求header中
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }

    }

    public static void main(String[] args) {
        String pswd = DigestUtils.md5DigestAsHex(("1722" + "1234").getBytes());
        System.out.println("pswd = " + pswd);
    }
}
